<?php

namespace App\Admin\Forms;

use App\Admin\Renderable\UserTable;
use App\Models\Project;
use App\Models\ProjectUser;
use App\Models\User;
use Carbon\Carbon;
use Dcat\Admin\Form\Row;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Widgets\Form;
use Exception;

class ChooseDoctorForm extends Form
{
    /**
     * 处理表单提交逻辑.
     *
     * @param array $input
     *
     * @return JsonResponse
     */
    public function handle(array $input): JsonResponse
    {

        try {

            $project_id = $input['project_id'] ?? null;
            $user_id = $input['doctor'] ?? null;

            $insert = [];
            foreach ($user_id as $key => $val) {
                $insert[$key]['project_id'] = $project_id;
                $insert[$key]['user_id'] = $val;
                $insert[$key]['created_at'] = date('Y-m-d H:i:s', time());
                $insert[$key]['updated_at'] = date('Y-m-d H:i:s', time());
            }

            $project = Project::find($project_id);

            // if (!empty($project->project_end_time)) {
            if (!empty($project->submit_info_end_time)) {
                // if (Carbon::now() > $project->project_end_time) {
                if (Carbon::now() > $project->submit_info_end_time) {
                    return $this->response()->error('项目资料收集已结束');
                }
            }

            $number_of_attendees = $project->number_of_attendees ?? 0;
            if ($number_of_attendees > 0) {
                // 原本有几条
                $projectUserCount = ProjectUser::where('project_id', $project_id)->get()->toArray();

                $count = 0;
                $insertCount = count($insert);
                foreach ($projectUserCount as $key => $val) {
                    foreach ($insert as $k => $v) {
                        if ($val['user_id'] == $v['user_id']) {
                            $count += 1;
                            unset($insert[$k]);
                        } else {
                            // dump($v);
                        }
                    }
                }

                // dump(count($projectUserCount));
                // dump($insertCount);
                // dump($count);
                // dd((count($projectUserCount) + ($insertCount - $count)));
                if ((count($projectUserCount) + ($insertCount - $count)) > $number_of_attendees) {
                    return $this->response()->error('参会人数已到最大值,请去掉' . (count($projectUserCount) + ($insertCount - $count)) - $number_of_attendees  . '个人');
                }
            }

            if (ProjectUser::where('project_id', $project_id)->exists()) {
                $newData = array_merge(ProjectUser::where('project_id', $project_id)->get()->toArray(), $insert);

                foreach ($newData as $key => &$val) {
                    unset($val['id'], $val['deleted_at']);
                }

                if (ProjectUser::where('project_id', $project_id)->forceDelete()) {

                    $res = ProjectUser::insert($newData);
                    if ($res) {
                        $return = $this->response()
                            ->success('成功')
                            ->refresh();
                    } else {
                        $return = $this->response()
                            ->error('失败1')
                            ->refresh();
                    }
                }
            } else {
                $res = ProjectUser::insert($insert);
                if ($res) {
                    $return = $this->response()
                        ->success('成功')
                        ->refresh();
                } else {
                    $return = $this->response()
                        ->error('失败1')
                        ->refresh();
                }
            }
        } catch (Exception $e) {
            $return = $this
                ->response()
                ->error(trans('main.fail') . $e->getMessage());
        }

        return $return;
    }


    public function form()
    {
        // 获取外部传递参数
        $id = request()->input('project_id') ?? null;
        // 分配的人
        $this->multipleSelect('doctor', '请选择医生')->options(User::getDoctor());
        $this->hidden('project_id')->value($id);
    }

    // 返回表单数据，如不需要可以删除此方法
    public function
    default()
    {
        // 获取外部传递参数
        $id = request()->input('project_id') ?? null;
        $doctor = ProjectUser::where('project_id', $id)->pluck('user_id');

        return [
            'project_id'         => $id,
            'doctor' => $doctor,
        ];
    }
}
